<?php
namespace Weixin\Controller;

use Think\Controller;

class WxMenuController extends Controller {
	CONST API_WEIXIN_URL = 'https://api.weixin.qq.com/cgi-bin/menu/';
	public function index() {
		
		// 先取出所有的父菜单
		$where = array (
				'parentId' => 0,
				'menuState' => 1 
		); // menuStort
		$m = M ( 'wx_menu' );
		$parentMenu = $m->where ( $where )->order ( 'menuStort asc' )->select ();
// 		p($parentMenu);
		foreach ( $parentMenu as $key => $val ) {
			$where = array (
					'parentId' => $parentMenu [$key] ['id'] 
			); // menuStort
			$childrenMenu = $m->where ( $where )->order ( 'menuStort asc' )->select ();
			$parentMenu [$key] ['urlAndkey'] = $childrenMenu;
		}
		$this->assign ( "all_menu", $parentMenu );
		$this->display ();
	}
	public function ajaxShowMenu() {
		$where = array (
				'parentId' => 0,
				'menuState' => 1 
		); // menuStort
		$m = M ( 'wx_menu' );
		$parentMenu = $m->where ( $where )->order ( 'menuStort asc' )->select ();
		
		foreach ( $parentMenu as $key => $val ) {
			$where = array (
					'parentId' => $parentMenu [$key] ['id'] 
			); // menuStort
			$childrenMenu = $m->where ( $where )->order ( 'menuStort asc' )->select ();
			$parentMenu [$key] ['urlAndkey'] = $childrenMenu;
		}
		
		echo (json_encode ( $parentMenu ));
		exit ();
	}
	public function addWxMenu() {
		if (! IS_POST) {
			if (isset ( $_GET ['parent_id'] )) {
				$parent_id = $_GET ['parent_id'];
			} else {
				$parent_id = 0;
			}
			$this->assign ( "parentId", $parent_id );
			
			$m = M ( 'wx_menu' );
			$where = array (
					'parentId' => 0,
					'menuState' => 1 
			); // menuStort
			$parentMenu = $m->where ( $where )->order ( 'menuStort asc' )->select ();
			$this->assign ( "parentMenu", $parentMenu );
			
// 			echo "<br/>parent_id:".$parent_id;
// 			p($parentMenu);
			
			$this->display ( "add_wx_menu" );
			exit ();
		} else {
			
			$menuName = $_POST ['menuName'];
			$menuAction = $_POST ['menuAction'];
			if ($menuAction == "view") {
				$urlAndkey = $_POST ['url'];
			} else {
				$urlAndkey = $_POST ['key'];
			}
			$data = array (
					'parentId' => trim ( $_POST ['parent_id'] ),
					'menuName' => trim ( $menuName ),
					'menuAction' => trim ( $menuAction ),
					'urlAndkey' => trim ( $urlAndkey ),
					'menuState' => trim ( $_POST ['menuState'] ),
					'menuStort' => trim ( $_POST ['menuStort'] ) 
			);
			
			$m = M ( 'wx_menu' );
			
			$addFlag = $m->add ( $data );
			
			if ($addFlag) {
				$this->success ( '添加菜单成功！' );
			} else {
				$this->error ( '删除菜单失败！' );
			}
		}
	}
	public function editWxMenu() {
		$id = empty ( $_GET ['id'] ) ? 0 : intval ( $_GET ['id'] );
		if (! IS_POST) {
			$m = M ( 'wx_menu' );
			$one_menu = $m->where ( array (
					'id' => $id 
			) )->find ();
			$where = array (
					'parentId' => 0,
					'menuState' => 1 
			); // menuStort
			$parentMenu = $m->where ( $where )->order ( 'menuStort asc' )->select ();
			
			$this->assign ( "parentMenu", $parentMenu );
			$this->assign ( "one_menu", $one_menu );
			$this->display ( "edit_wx_menu" );
			exit ();
		} else {
			$menuName = $_POST ['menuName'];
			$menuAction = $_POST ['menuAction'];
			if ($menuAction == "view") {
				$urlAndkey = $_POST ['url'];
			} else {
				$urlAndkey = $_POST ['key'];
			}
			$data = array (
					'parentId' => trim ( $_POST ['parent_id'] ),
					'menuName' => trim ( $menuName ),
					'menuAction' => trim ( $menuAction ),
					'urlAndkey' => trim ( $urlAndkey ),
					'menuState' => trim ( $_POST ['menuState'] ),
					'menuStort' => trim ( $_POST ['menuStort'] ) 
			);
			
			$m = M ( 'wx_menu' );
			$addFlag = $m->where ( 'id=' . $id )->save ( $data );
			
			if ($addFlag) {
				$this->success ( '编辑菜单成功！' );
			} else {
				$this->error ( '编辑菜单失败！' );
			}
		}
	}
	public function deleteWxMenu() {
		$id = empty ( $_GET ['id'] ) ? 0 : intval ( $_GET ['id'] );
		$type = $_GET ['type'];
		
		$m = M ( 'wx_menu' );
		
		if ($type == "parent_menu") {
			$where = array (
					'parentId' => $id,
					'id' => $id,
					'_logic' => 'OR' 
			);
			$deleteFlag = $m->where ( $where )->delete ();
		} else if ($type == "children_menu") {
			$where = array (
					'id' => $id 
			);
			$deleteFlag = $m->where ( $where )->delete ();
		} else {
			$deleteFlag = 0;
		}
		
		if ($deleteFlag) {
			$this->success ( '删除菜单成功！' );
		} else {
			$this->error ( "删除菜单失败！" );
		}
	}
	public function ajaxEditMenu() {
		if (isset ( $_GET ['id'] )) {
			$id = $_GET ['id'];
		} else {
			$id = null;
		}
		if (isset ( $_GET ['column'] )) {
			$column_name = $_GET ['column'];
		} else {
			$column_name = null;
		}
		if (isset ( $_GET ['value'] )) {
			$column_value = $_GET ['value'];
		} else {
			$column_value = null;
		}
		
		$m = M ( 'wx_menu' );
		
		$data = array (
				$column_name => $column_value 
		);
		$updateFlag = $m->where ( 'id=' . $id )->save ( $data );
		
		if ($updateFlag) {
			echo $updateFlag;
		} else {
			echo 0;
		}
		exit ();
	}
	
	public function createMenu() {
		// 创建菜单
		$this->createMenuXml ();
		$createMenuFlag = $this->create ();
		/**
		 * $createMenuFlag 为-1时，则没找到token.xml
		 * -2时，没找到menu.xml
		 * -3时，没有access_token
		 * 0时，菜单创建成功
		 * 其他，微信错误码
		 */
		if ($createMenuFlag == - 1) {
			$this->error ( '没有找到token.xml文件！' );
		} else if ($createMenuFlag == - 2) {
			$this->error ( '没有找到menu.xml文件！' );
		} else if ($createMenuFlag == - 3) {
			$this->error ( 'access_token为空！' );
		} else if ($createMenuFlag == 0) {
			$this->success ( "创建菜单成功!" );
		} else {
			$this->success ( "创建菜单失败!错误码：" . $createMenuFlag );
		}
	}
	public function deleteMenu() {
		// 删除菜单
		$createMenuFlag = $this->delete ();
		/**
		 * $createMenuFlag 为-1时，则没找到token.xml
		 * -2时，没找到menu.xml
		 * -3时，没有access_token
		 * 0时，菜单创建成功
		 * 其他，微信错误码
		 */
		if ($createMenuFlag == - 1) {
			$this->error ( '没有找到token.xml文件！' );
		} else if ($createMenuFlag == - 2) {
			$this->error ( '没有找到menu.xml文件！' );
		} else if ($createMenuFlag == - 3) {
			$this->error ( 'access_token为空！' );
		} else if ($createMenuFlag == 0) {
			$this->success ( "删除菜单成功!" );
		} else {
			$this->success ( "删除菜单失败!错误码：" . $createMenuFlag );
		}
	}
	
	/**
	 * 创建自动定义菜单
	 */
	public function createMenuXml() {
		$doc = new \DOMDocument ( "1.0", "utf-8" );
		$doc->formatOutput = true; // 设置可输出操作
		$root = $doc->createElement ( "root" ); // 设置根节点
		$root = $doc->appendChild ( $root ); // 添加根节点
		
		$m = M ( 'wx_menu' );
		$where = array (
				'parentId' => 0,
				'menuState' => 1 
		); // menuStort
		$parentMenus = $m->where ( $where )->order ( 'menuStort asc' )->select ();
		
		for($i = 0; $i < count ( $parentMenus ); $i ++) {
			$rowParent = $parentMenus [$i];
			// 创建menu节点
			$menu = $doc->createElement ( "menu" );
			$menu = $root->appendChild ( $menu );
			
			$name = $doc->createElement ( "name" ); // 创建父节点name
			$name = $menu->appendChild ( $name ); // 把节点添加到menu节点的子节点
			$name->appendChild ( $doc->createTextNode ( $rowParent ['menuName'] ) );
			
			$m = M ( 'wx_menu' );
			$where = array (
					'parentId' => $rowParent ['id'],
					'menuState' => 1 
			); // menuStort
			$childMenus = $m->where ( $where )->order ( 'menuStort asc' )->select ();
			
			if (! empty ( $childMenus )) {
				for($j = 0; $j < count ( $childMenus ); $j ++) {
					$rowChild = $childMenus [$j];
					// 创建子节点
					$sub = $doc->createElement ( "sub" );
					$sub = $menu->appendChild ( $sub );
					$name = $doc->createElement ( "name" ); // 创建父节点name
					$name = $sub->appendChild ( $name ); // 把节点添加到menu节点的子节点
					$name->appendChild ( $doc->createTextNode ( $rowChild ['menuName'] ) );
					
					$type = $doc->createElement ( "type" ); // 创建父节点name
					$type = $sub->appendChild ( $type ); // 把节点添加到menu节点的子节点
					$type->appendChild ( $doc->createTextNode ( $rowChild ['menuAction'] ) );
					
					if ($rowChild ['menuAction'] == "click") {
						$key = $doc->createElement ( "key" ); // 创建父节点name
						$key = $sub->appendChild ( $key ); // 把节点添加到menu节点的子节点
						$key->appendChild ( $doc->createTextNode ( $rowChild ['urlAndkey'] ) );
					} else {
						$url = $doc->createElement ( "url" ); // 创建父节点name
						$url = $sub->appendChild ( $url ); // 把节点添加到menu节点的子节点
						$url->appendChild ( $doc->createTextNode ( $rowChild ['urlAndkey'] ) );
					}
				}
			} else {
				$type = $doc->createElement ( "type" ); // 创建父节点name
				$type = $menu->appendChild ( $type ); // 把节点添加到menu节点的子节点
				$type->appendChild ( $doc->createTextNode ( $rowParent ['menuAction'] ) );
				if ($rowParent ['menuAction'] == "click") {
					$key = $doc->createElement ( "key" ); // 创建父节点name
					$key = $menu->appendChild ( $key ); // 把节点添加到menu节点的子节点
					$key->appendChild ( $doc->createTextNode ( $rowParent ['urlAndkey'] ) );
				} else {
					$url = $doc->createElement ( "url" ); // 创建父节点name
					$url = $menu->appendChild ( $url ); // 把节点添加到menu节点的子节点
					$url->appendChild ( $doc->createTextNode ( $rowParent ['urlAndkey'] ) );
				}
			}
		}
		
		$file_path = C ( 'wesetDir' );
		$doc->save ( $file_path . "/lib/config/menu.xml" );
	}
	private $token;
	private $menu_arr = array ();
	public function create() {
		// 设置TOKEN
		/**
		 * 先判断文件是否存在，如果存在取出时间看有没有过期
		 * 如果过期就再次去获取，没有则用xml文件中的
		 */
		$time = time ();
		
		$ACC_TOKEN = $this->getAccessToken();
		
		if (! empty ( $ACC_TOKEN )) {
			$url = self::API_WEIXIN_URL . 'create?access_token=' . $ACC_TOKEN;
			// 获取XML中的菜单数据
			$menu_path = $file_path . '/config/menu.xml';
			if (! file_exists ( $menu_path )) {
				return - 2;
				exit ();
			}
			$xml_array = ( array ) simplexml_load_file ( $menu_path );
			$xml_menus = $xml_array ['menu'];
			
			$menu_arr_0 = array (
					'name' => ( string ) $xml_menus [0]->name 
			); // 一级菜单
			$menu_arr_1 = array (
					'name' => ( string ) $xml_menus [1]->name 
			); // 一级菜单
			$menu_arr_2 = array (
					'name' => ( string ) $xml_menus [2]->name 
			); // 一级菜单
			if (empty ( $xml_menus [0]->sub )) {
				if(!empty($xml_menus [0]->type)){
					$menu_arr_0 ['type'] = ( string ) $xml_menus [0]->type;
					if ($menu_arr_0 ['type'] == 'click') {
						$menu_arr_0 ['key'] = ( string ) $xml_menus [0]->key;
					} else {
						$menu_arr_0 ['url'] = ( string ) $xml_menus [0]->url;
					}
				}
			} else {
				$menu_arr_0 ['sub_button'] = array ();
				$sub = $xml_menus [0]->sub;
				for($i = 0, $num = count ( $sub ); $i < $num; $i ++) {
					if (( string ) $sub [$i]->type == 'click') {
						$menu_arr_0 ['sub_button'] [] = array (
								'name' => ( string ) $sub [$i]->name,
								'type' => ( string ) $sub [$i]->type,
								'key' => ( string ) $sub [$i]->key 
						);
					} else {
						$menu_arr_0 ['sub_button'] [] = array (
								'name' => ( string ) $sub [$i]->name,
								'type' => ( string ) $sub [$i]->type,
								'url' => ( string ) $sub [$i]->url 
						);
					}
				}
			}
			if (empty ( $xml_menus [1]->sub )) {
				
				if(!empty($xml_menus [1]->type)){
					$menu_arr_1 ['type'] = ( string ) $xml_menus [1]->type;
					if ($menu_arr_1 ['type'] == 'click') {
						$menu_arr_1 ['key'] = ( string ) $xml_menus [1]->key;
					} else {
						$menu_arr_1 ['url'] = ( string ) $xml_menus [1]->url;
					}
				}
				
			} else {
				$menu_arr_1 ['sub_button'] = array ();
				$sub = $xml_menus [1]->sub;
				for($i = 0, $num = count ( $sub ); $i < $num; $i ++) {
					if (( string ) $sub [$i]->type == 'click') {
						$menu_arr_1 ['sub_button'] [] = array (
								'name' => ( string ) $sub [$i]->name,
								'type' => ( string ) $sub [$i]->type,
								'key' => ( string ) $sub [$i]->key 
						);
					} else {
						$menu_arr_1 ['sub_button'] [] = array (
								'name' => ( string ) $sub [$i]->name,
								'type' => ( string ) $sub [$i]->type,
								'url' => ( string ) $sub [$i]->url 
						);
					}
				}
			}
			if (empty ( $xml_menus [2]->sub )) {
				
				if(!empty($xml_menus [2]->type)){
					$menu_arr_2 ['type'] = ( string ) $xml_menus [2]->type;
					if ($menu_arr_2 ['type'] == 'click') {
						$menu_arr_2 ['key'] = ( string ) $xml_menus [2]->key;
					} else {
						$menu_arr_2 ['url'] = ( string ) $xml_menus [2]->url;
					}
				}
				
			} else {
				$menu_arr_2 ['sub_button'] = array ();
				$sub = $xml_menus [2]->sub;
				for($i = 0, $num = count ( $sub ); $i < $num; $i ++) {
					if (( string ) $sub [$i]->type == 'click') {
						$menu_arr_2 ['sub_button'] [] = array (
								'name' => ( string ) $sub [$i]->name,
								'type' => ( string ) $sub [$i]->type,
								'key' => ( string ) $sub [$i]->key 
						);
					} else {
						$menu_arr_2 ['sub_button'] [] = array (
								'name' => ( string ) $sub [$i]->name,
								'type' => ( string ) $sub [$i]->type,
								'url' => ( string ) $sub [$i]->url 
						);
					}
				}
			}
			if(!empty($menu_arr_0['name'])){
				array_push ( $this->menu_arr, $menu_arr_0 );
			}
			if(!empty($menu_arr_1['name'])){
				array_push ( $this->menu_arr, $menu_arr_1 );
			}
			if(!empty($menu_arr_2['name'])){
				array_push ( $this->menu_arr, $menu_arr_2 );
			}
			
			$data = array (
				'button' => $this->menu_arr 
			);
			
			$data_string = ($this->var_json_encode ( ($data) ));
			$data_string = str_replace ( " ", "", $data_string );
			$data_string = str_replace ( "&amp;", "&", $data_string );
			

			$ch = curl_init ();
			curl_setopt ( $ch, CURLOPT_TIMEOUT, 300 );
			curl_setopt ( $ch, CURLOPT_URL, $url ); // 登录提交的地址
			curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true ); // 获取数据返回
			curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
			curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
			curl_setopt ( $ch, CURLOPT_POST, TRUE );
			curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data_string ); // 要提交的信息
			curl_setopt ( $ch, CURLOPT_HTTPHEADER, array (
					'Content-Type: application/json',
					'Content-Length: ' . strlen ( $data_string ) 
			) );
			$result = curl_exec ( $ch );
			$return = json_decode ( $result, true );
			return $return ['errcode'];
			exit ();
		} else {
			return - 3;
			exit ();
		}
	}
	
	private function getAccessToken() {
		$file_path = C ( 'wesetDir' ) . '/lib';
		if (file_exists ( $file_path . "/config/token.xml" )) {
			// 文件存在,解析xml文件取出时间
			$token_arr = ( array ) simplexml_load_file ( $file_path . "/config/token.xml" );
			if (($time - $token_arr ['time']) > 300) {
				// 超时
				// 取出的appid和appsecret
				$xml_path = $file_path . "/config/app.xml";
				if (file_exists ( $xml_path )) {
					$app_xml = ( array ) simplexml_load_file ( $xml_path );
					$appId = $app_xml ['appId'];
					$appSecret = $app_xml ['appSecret'];
				} else {
					return - 1;
					exit ();
				}
				$TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appId . "&secret=" . $appSecret;
				$json = httpGet ( $TOKEN_URL );
				$result = json_decode ( $json, true );
				$ACC_TOKEN = $result ['access_token'];
				$this->createAccessTokenXml ( $ACC_TOKEN, $time );
			} else {
				// 没有超时
				$ACC_TOKEN = $token_arr ['access_token'];
			}
		} else {
			// 取出的appid和appsecret
			$xml_path = $file_path . "/config/app.xml";
			if (file_exists ( $xml_path )) {
				$app_xml = ( array ) simplexml_load_file ( $xml_path );
				$appId = $app_xml ['appId'];
				$appSecret = $app_xml ['appSecret'];
			} else {
				return - 1;
				exit ();
			}
			$TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appId . "&secret=" . $appSecret;
			$json = httpGet ( $TOKEN_URL );
			$result = json_decode ( $json, true );
			$ACC_TOKEN = $result ['access_token'];
			$this->createAccessTokenXml ( $ACC_TOKEN, $time );
		}
		
		return $ACC_TOKEN;
	}
	
	public function delete() {
		/**
		 * 先判断文件是否存在，如果存在取出时间看有没有过期
		 * 如果过期就再次去获取，没有则用xml文件中的
		 */
		$time = time ();
		$ACC_TOKEN = $this->getAccessToken();
		
		if (! empty ( $ACC_TOKEN )) {
			$MENU_URL = self::API_WEIXIN_URL . 'delete?access_token=' . $ACC_TOKEN;
			
			$cu = curl_init ();
			curl_setopt ( $cu, CURLOPT_URL, $MENU_URL );
			curl_setopt ( $cu, CURLOPT_RETURNTRANSFER, 1 );
			curl_setopt ( $cu, CURLOPT_SSL_VERIFYPEER, FALSE );
			curl_setopt ( $cu, CURLOPT_SSL_VERIFYHOST, FALSE );
			$result = curl_exec ( $cu );
			$return = json_decode ( $result, true );
			curl_close ( $cu );
			return $return ['errcode'];
			exit ();
		} else {
			return - 3;
			exit ();
		}
	}
	private function var_urlencode($var) {
		if (is_array ( $var )) {
			foreach ( $var as $k => $v ) {
				if (is_scalar ( $v )) {
					$var [$k] = urlencode ( $v );
				} else {
					$var [$k] = $this->var_urlencode ( $v );
				}
			}
		} else {
			$var = urlencode ( $var );
		}
		return $var;
	}
	private function var_json_encode($var) {
		$_var = $this->var_urlencode ( $var );
		$_str = json_encode ( $_var );
		return urldecode ( $_str );
	}
	
	/**
	 *
	 * @param $access_token 存放access_token        	
	 * @param $time 存放access_token的时间        	
	 */
	public function createAccessTokenXml($access_token, $time) {
		$doc = new \DOMDocument ( "1.0", "utf-8" );
		$doc->formatOutput = true; // 设置可输出操作
		$root = $doc->createElement ( "root" ); // 设置根节点
		$root = $doc->appendChild ( $root ); // 添加根节点
		$name = $doc->createElement ( "access_token" ); // 创建父节点name
		$name = $root->appendChild ( $name ); // 把节点添加到menu节点的子节点
		$name->appendChild ( $doc->createTextNode ( $access_token ) );
		
		$type = $doc->createElement ( "time" ); // 创建父节点name
		$type = $root->appendChild ( $type ); // 把节点添加到menu节点的子节点
		$type->appendChild ( $doc->createTextNode ( $time ) );
		$file_path = C ( 'wesetDir' ) . '/lib';
		$doc->save ( $file_path . "/config/token.xml" );
	}
}